#include "./draw_task.h"
#include "../../driver/heat/parts.h"
#include "../../driver/heat/sensor.h"
#include "../../utils/progress.h"

namespace task {

using namespace driver;
using namespace utils;

void DrawTask::change() {
    if (m_bucket == Bucket::ID1) {
        m_bucket = Bucket::ID2;
    } else {
        m_bucket = Bucket::ID1;
    }
}

void DrawTask::open() {
    if (m_bucket == Bucket::ID1) {
        parts->bucket1_pump_open();
    } else {
        parts->bucket2_pump_open();
    }
}

void DrawTask::close() {
    parts->bucket1_pump_close();
    parts->bucket2_pump_close();
}

void DrawTask::run() {
    
    for (;;) {
        switch (m_state) {
            case State::IDLE: do_idle(); break;
            case State::WORK: do_work(); break;
            case State::STOP: do_stop(); break;
        }
    }
}

void DrawTask::do_idle() {
    uint32_t cond_count = 0;
    for (;;) {
        if (!sensor->is_bucket_high()) {
            cond_count ++;
            if (cond_count >= 5) {
                m_state = State::WORK;
                break;
            }
        } else {
            cond_count = 0;
        }

        if (wait(1000)) {
            return;
        }
    }
}

void DrawTask::do_work() {
    Progress prog;
    open();
    for (;;) {
        if (sensor->is_bucket_high()) {
            m_state = State::IDLE;
            break;
        }

        if (prog.is_after(DRAW_TIMEOUT)) {
            change();
            break;
        }

        if (wait(1000)) {
            break;
        }
    }
    close();
}

void DrawTask::do_stop() {
    close();
    wait();
}

}










